package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {

    private static String[] notchechUris = new String[]{
            "/backend/**",
            "/front/**",
            "/common",
            "/employee/login",
            "/employee/logout"
    };

    private  static  final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取 url
        String requestURI = req.getRequestURI();
        //判断是否需要校验
        boolean check = check(requestURI);
        //放行
        if (!check){
            chain.doFilter(req,resp);
            return;
        }
        //查看登录状态
        if (req.getSession().getAttribute("employee")!=null){

            Long currentId=(Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(currentId);
            chain.doFilter(req,resp);
            BaseContext.removeCurrentId();
            return;
        }
        //返回未登录结果，页面跳转
        R result = R.error("NOTLOGIN");
        resp.getWriter().write(JSON.toJSONString(result));
        return;
    }

    private boolean check(String requestURI) {
        for (String uri : notchechUris) {
             if (PATH_MATCHER.match(uri,requestURI)){
                 //不需要校验
                 return false;
             }
        }
        return true;
    }
}
